package com.molamil.outboard {
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.Event;
	import flash.net.Socket;

	/**
	 * @author martindyrby
	 */
	[Event(name = "connect", type="flash.event.Event")]
	[Event(name = "ioError", type="flash.event.IOErrorEvent")]
	public class OutboardSocketService extends EventDispatcher implements IOutboardService {
		protected var socket : Socket;
		protected var outboardhost : Outboard;

		public function init(host : String, port : uint) : void {
			if(socket == null) {
				socket = new Socket();
				socket.addEventListener(Event.CONNECT, connectHandler);
				socket.addEventListener(IOErrorEvent.IO_ERROR, iOErrorHandler);
				socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
				socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(event:Event):void { trace(event); }, false, 0, true)
				socket.connect(host, port);
			}
		}
		
		public function set host(value : Outboard) : void {
			outboardhost = value;
		}
		
		public function destroy() : void {
			socket.removeEventListener(Event.CONNECT, connectHandler);
			socket.removeEventListener(IOErrorEvent.IO_ERROR, iOErrorHandler);
			socket.removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}

		protected function socketDataHandler(event : ProgressEvent) : void {
			trace(event);
		}

		private function iOErrorHandler(event : IOErrorEvent) : void {
			trace(event);
			dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
		}

		private function connectHandler(event : Event) : void {
			trace(event);
			dispatchEvent(new Event(Event.CONNECT));
		}
	}
}
